﻿/*  DISCLAIMER ***

    Copyright (c) 2014 Michael T. Joiner

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
    to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
    and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  
 */

#region Using Statements

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Reflection;
using System.Windows.Threading;

#endregion

namespace Application.SceneEditor.Data
{
    /// <summary>
    /// Object which represents the base used for notifying property changes to the UI
    /// </summary>
    public abstract class BaseNotifier : DynamicObject, INotifyPropertyChanged
    {
        #region Properties

        /// <summary>
        /// Gets a value indicating the Dispatcher object, which this object was created with
        /// </summary>
        public Dispatcher Dispatcher { get { return m_Dispatcher; } }

        // Interface implementation for INotifyPropertyChanged
        event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
        {
            add
            {
                if (!m_ChangeHandlers.Contains(value))
                {
                    m_ChangeHandlers.Add(value);
                    m_PropertyChanged += value;
                }
            }

            remove
            {
                if (m_ChangeHandlers.Contains(value))
                {
                    m_ChangeHandlers.Remove(value);
                    m_PropertyChanged -= value;
                }
            }
        }

        #endregion

        #region Methods

        #region Constructor

        /// <summary>
        /// Constructs a new instance of this object
        /// </summary>
        public BaseNotifier()
        {
            this.m_Dispatcher = Dispatcher.CurrentDispatcher;
            this.m_ChangeHandlers = new List<PropertyChangedEventHandler>();
            this.m_DynamicProperties = new Dictionary<string, object>();
        }

        #endregion

        /// <summary>
        /// Adds the object as the base object
        /// </summary>
        /// <typeparam name="T">indicates the type of object the value represents</typeparam>
        /// <param name="value">the actual object to get the property values from</param>
        public void GenerateProperties<T>(T value)
        {
            var type = typeof(T);
            var propertiesInfoCollection = type.GetProperties();

            foreach(var propInfo in propertiesInfoCollection)
            {
                var propValue = propInfo.GetValue(value);
                SetPropertyValue(propInfo.Name, propValue);
            }
        }

        /// <summary>
        /// Sets a value for a property with the supplied name, or creates a property if it does not exist
        /// </summary>
        /// <param name="propertyName">a string value representing the name of the property to set</param>
        /// <param name="value">an object which represents the data being store for the property name</param>
        public void SetPropertyValue(string propertyName, object value)
        {
            if (m_DynamicProperties.ContainsKey(propertyName))
                m_DynamicProperties[propertyName] = value;

            else m_DynamicProperties.Add(propertyName, value);

            NotifyPropertyChanged(propertyName);
        }

        /// <summary>
        /// Returns an object stored in the slot with the the supplied key name
        /// </summary>
        /// <param name="propertyName">a string value representing the name of the property to return</param>        
        public object GetPropertyValue(string propertyName)
        {
            return m_DynamicProperties.ContainsKey(propertyName) ? m_DynamicProperties[propertyName] : null;
        }

        /// <summary>
        /// Provides the implementation for operations that get member values. Classes derived from the DynamicObject
        /// class can override this method to specify dynamic behavior for operations such as getting a value for a property
        /// </summary>
        /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed</param>
        /// <param name="result">The result of the get operation. For example, if the method is called for a property</param>        
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            var retValue = base.TryGetMember(binder, out result);

            if (!retValue)
            {
                result = GetPropertyValue(binder.Name);

                if (result != null)
                    retValue = true;
            }

            return retValue;
        }

        /// <summary>
        /// Provides the implementation for operations that set member values. Classes derived from the DynamicObject
        /// class can override this method to specify dynamic behavior for operations such as setting a value for a property
        /// </summary>
        /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed</param>
        /// <param name="result">The result of the get operation. For example, if the method is called for a property</param>  
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            var retValue = base.TrySetMember(binder, value);

            if (!retValue)
            {
                SetPropertyValue(binder.Name, value);
                retValue = true;
            }

            return retValue;
        }

        /// <summary>
        /// Notifies the PropertyChanged event handler for this object
        /// </summary>
        /// <param name="propertyName">a string value representing the name of the property which has changed</param>
        protected virtual void NotifyPropertyChanged(string propertyName)
        {
            // Do we have something that is handling this change?
            if (m_PropertyChanged != null)
            {
                // create a temp variable for the eventargs object
                var args = new PropertyChangedEventArgs(propertyName);

                // Check to see if we are on the UI thread
                if (m_Dispatcher.CheckAccess())
                    m_PropertyChanged.Invoke(this, args);

                // well, dispatch the request on the UI thread
                else m_Dispatcher.Invoke(m_PropertyChanged, this, args);
            }
        }

        /// <summary>
        /// Removes all PropertyChange handlers from this object. used for cleanup on unloading this object
        /// </summary>
        protected void ReleaseHandlers()
        {
            // Remove all handlers from the PropertyChanged event handler
            foreach (var handler in m_ChangeHandlers)
                m_PropertyChanged -= handler;

            // Clear the list of handlers
            m_ChangeHandlers.Clear();
        }

        #endregion

        private Dispatcher m_Dispatcher;
        protected object SyncContext = new object();
        private event PropertyChangedEventHandler m_PropertyChanged;
        private List<PropertyChangedEventHandler> m_ChangeHandlers;
        private Dictionary<string, object> m_DynamicProperties;
    }
}
